package com.yanggu.jt808.model.resp;

import com.yanggu.jt808.consts.Jt808Constant;
import com.yanggu.jt808.model.base.DataPackage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.Data;
import org.junit.platform.commons.util.StringUtils;

/**
 * 注册响应包
 *
 * @Description RegisterResp
 * @Author guoyb
 * @Date 2023/11/9 14:52
 */
@Data
public class RegisterResp extends DataPackage {

    public static final byte SUCCESS = 0;//成功
    public static final byte VEHICLE_ALREADY_REGISTER = 1;//车辆已被注册
    public static final byte NOT_IN_DB = 2;//数据库无该车辆
    public static final byte TERMINAL_ALREADY_REGISTER = 3;//终端已被注册

    private int replyFlowId; //应答流水号 2字节,对应终端流水号
    private byte result;    //结果 1字节
    private String authCode; //鉴权码


    public RegisterResp() {
        this.getHeader().setMsgId(Jt808Constant.终端注册应答);
    }

    @Override
    public ByteBuf toByteBufMsg() {

        ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
        //写入消息体
        buf.writeShort(replyFlowId);
        buf.writeByte(result);
        if (result == SUCCESS && StringUtils.isNotBlank(authCode)) {//成功才写入鉴权码
            buf.writeBytes(authCode.getBytes(Jt808Constant.DEFAULT_CHARSET));
        }
        super.setMsgBody(buf);
        return super.toByteBufMsg();
    }

    public static RegisterResp response(DataPackage msg, int flowId) {
        RegisterResp resp = new RegisterResp();

        //设置一些参数
        resp.copyBy(msg,flowId);
        //应答流水号
        resp.setReplyFlowId(msg.getHeader().getFlowId());

        return resp;
    }
}
